const bcrypt = require("bcryptjs");
const User = require("../models/user");

exports.searchUsers = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, username, email } = req.body;
    const result = await User.searchUsers({ page, pageSize, username, email });
    res.json({
      data: result.data,
      total: result.total,
      page: result.page,
      pageSize: result.pageSize,
    });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.getAllUsers = async (req, res) => {
  try {
    const users = await User.findAll();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.getUserById = async (req, res) => {
  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ error: "用户不存在" });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.createUser = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    // 验证必填字段
    if (!username || !email || !password) {
      return res.status(400).json({ error: "缺少必填字段" });
    }
    // 验证邮箱格式
    if (!validateEmail(email)) {
      return res.status(400).json({ error: "邮箱格式不正确" });
    }
    const existingUser = await User.findByEmail(email);
    if (existingUser) {
      return res.status(400).json({ error: "该邮箱已被注册" });
    }
    const hashedPassword = await bcrypt.hash(password, 8);
    const userId = await User.create({
      username,
      email,
      password: hashedPassword,
    });
    // 返回时移除敏感信息
    res.status(201).json({
      message: "用户创建成功",
      data: {
        id: userId,
        username,
        email,
      },
    });
  } catch (error) {
    console.error("注册失败：", error);
    res.status(500).json({ error: "内部服务错误" });
  }
};

// 邮箱验证辅助函数
function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(String(email).toLowerCase());
}

exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { username, email, password } = req.body;
    // 构建更新数据对象
    const updateData = { username, email };
    // 如果存在密码则进行加密
    if (password) {
      updateData.password = await bcrypt.hash(password, 8);
    }
    // 只更新需要修改的字段
    const result = await User.update(id, updateData);
    if (result) {
      res.json({ message: "用户更新成功" });
    } else {
      res.status(404).json({ error: "用户不存在" });
    }
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;
    await User.delete(id);
    res.json({ message: "用户删除成功" });
  } catch (error) {
    res.status(500).json({ error: "内部服务错误" });
  }
};

exports.deleteBatchUsers = async (req, res) => {
  try {
    const { ids } = req.body;
    if (!ids || !Array.isArray(ids)) {
      return res.status(400).json({ error: "无效的用户ID参数" });
    }
    if (ids.length === 0) {
      return res.status(400).json({ error: "未提供用户ID" });
    }
    // 验证ID格式
    if (ids.some((id) => isNaN(parseInt(id)))) {
      return res.status(400).json({ error: "包含无效的用户ID" });
    }
    const result = await User.deleteBatch(ids);
    if (result) {
      res.json({
        message: "批量删除成功",
        deletedCount: result, // 返回实际删除数量
      });
    } else {
      res.status(404).json({ error: "未找到匹配的用户" });
    }
  } catch (error) {
    console.error("批量删除失败:", error);
    res.status(500).json({
      error: "批量删除失败",
      detail: error.message,
    });
  }
};
